<template>
  <view class="search-box">
    <uni-search-bar :value="kw" @input="input" :radius="100" cancelButton="none"></uni-search-bar>
    <view v-if="searchResults.length>0" class="sugg-list">
      <view class="sugg-item" v-for="item in searchResults" :key="item.goods_id" @click="goToDetail(item.goods_id)">
        <text>{{item.goods_name}}</text>
        <uni-icons type="arrowright"></uni-icons>
      </view>
    </view>
    <view v-else class="history-box">
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="17" @click="clearHistory"></uni-icons>
      </view>
      <view class="history-list">
        <uni-tag v-for="(item,index) in history" @click="gotoGoodsList(item)" :key="index" :text="item"></uni-tag>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        isShowHistory: true,
        timer: null,
        kw: '',
        searchResults: [],
        historyList: []
      };
    },
    onLoad() {
      this.getSearchHistory()
    },
    computed: {
      history() {
        return [...this.historyList].reverse()
      }
    },
    methods: {
      input(e) {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.kw = e
          this.getSearchResults()
          this.isShowHistory = false
        }, 500)
        // // 清除 timer 对应的延时器
        // clearTimeout(this.timer)
        // // 重新启动一个延时器，并把 timerId 赋值给 this.timer
        // this.timer = setTimeout(() => {
        // // 如果 500 毫秒内，没有触发新的输入事件，则为搜索关键词赋值
        // this.kw = e
        // console.log(this.kw)
        // }, 500)

      },
      async getSearchResults() {
        if (this.kw === 0 || this.kw === '') {
          this.searchResults = []
          this.isShowHistory = true
          return
        }
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/qsearch', {
          query: this.kw
        })
        // 3.2 请求失败
        if (res.meta.status !== 200) return uni.$showMsg()
        // 3.3 请求成功，为 data 中的数据赋值
        this.searchResults = res.message
        this.saveSearchHistory()
      },
      goToDetail(goods_id) {
        uni.navigateTo({
          url: '../good_detail/good_detail?goods_id=' + goods_id
        })
      },
      saveSearchHistory() {

        const set = new Set(this.historyList)
        set.delete(this.kw)
        set.add(this.kw)
        this.historyList = Array.from(set)
        // 调用 uni.setStorageSync(key, value) 将搜索历史记录持久化存储到本地
        uni.setStorageSync('kw', JSON.stringify(this.historyList))

      },
      getSearchHistory() {
        if (uni.getStorageSync('kw') === '[]') return
        this.historyList = JSON.parse(uni.getStorageSync('kw'))
      },
      clearHistory() {
        uni.clearStorageSync('kw')
        this.historyList = []
      },
      gotoGoodsList(item) {
        this.kw = item
        this.getSearchResults()
      },
    }
  }
</script>

<style lang="scss">
  .search-box {
    position: sticky;
    top: 0;
    z-index: 999;

  }

  .sugg-list {
    padding: 0 5px;

    .sugg-item {
      font-size: 12px;
      padding: 13px 0;
      border-bottom: 1px solid #efefef;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .goods-name {
        // 文字不允许换行（单行文本）
        white-space: nowrap;
        // 溢出部分隐藏
        overflow: hidden;
        // 文本溢出后，使用 ... 代替
        text-overflow: ellipsis;
        margin-right: 3px;
      }
    }

    .history-box {
      padding: 0 5px;

      .history-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 40px;
        font-size: 13px;
        border-bottom: 1px solid #efefef;
      }
    }
  }
</style>
